package com.etone.smartAudit.service;

import com.alibaba.fastjson.JSON;
import com.etone.smartAudit.domain.Admin;
import com.etone.smartAudit.domain.FieldCase;
import com.etone.smartAudit.dto.fieldCase.FieldCaseDTO;
import com.etone.smartAudit.error.CustomParameterizedException;
import com.etone.smartAudit.mapper.FieldCaseMapper;
import com.etone.smartAudit.mapstruct.FieldCaseMapstruct;
import com.etone.smartAudit.utils.ArraysExtendUtil;
import com.etone.smartAudit.utils.ImageUtil;
import com.etone.smartAudit.vo.FileVO;
import com.etone.smartAudit.vo.PagerVO;
import com.etone.smartAudit.vo.fieldCase.ContributorTopVO;
import com.etone.smartAudit.vo.fieldCase.FieldCaseDetailVO;
import com.etone.smartAudit.vo.fieldCase.FieldCaseListVO;
import com.etone.smartAudit.vo.fieldCase.FieldCaseSimpleVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author: sovy
 * @date: 2020/8/18
 * @description:
 */
@Service
@AllArgsConstructor
public class FieldCaseService {
    private FieldCaseMapper fieldCaseMapper;

    private FieldCaseMapstruct fieldCaseMapstruct;

    private FileUploadService fileUploadService;


    /**
     * 案例列表
     *
     * @param fieldId
     * @param page
     * @param pageSize
     * @return
     */
    public PagerVO<FieldCaseListVO> findList(Integer fieldId, int page, int pageSize) {
        Page<FieldCaseListVO> fieldCaseListVOPage = PageHelper.startPage(page, pageSize).doSelectPage(() -> {
            fieldCaseMapper.findList(fieldId);
        });
        return PagerVO.of(fieldCaseListVOPage);
    }


    /**
     * @param fieldId
     * @param orderBy
     * @param page
     * @param pageSize
     * @return
     */
    public PagerVO<FieldCaseSimpleVO> listSimple(Integer fieldId, String orderBy, int page, int pageSize) {
        Page<FieldCaseSimpleVO> fieldCaseSimpleVOPage = PageHelper.startPage(page, pageSize).doSelectPage(() -> {
            fieldCaseMapper.findListSimple(fieldId, orderBy);
        });
        return PagerVO.of(fieldCaseSimpleVOPage);
    }

    /**
     * 案例详情
     *
     * @param id
     * @param isLook 是否记录统计次数
     * @return
     */
    public FieldCaseDetailVO getFieldCaseDetailVO(Integer id, Boolean isLook) {
        FieldCaseDetailVO fieldCaseDetailVOById = fieldCaseMapper.findFieldCaseDetailVOById(id);
        if (isLook) {
            fieldCaseMapper.addLookCnt(id, 1);
        }
        return fieldCaseDetailVOById;
    }

    /**
     * 案例详情
     *
     * @param id
     * @return
     */
    public FieldCase get(Integer id) {
        FieldCase fieldCase = fieldCaseMapper.selectById(id);
        if (fieldCase == null) {
            throw new CustomParameterizedException("案例不存在");
        }
        return fieldCase;
    }

    /**
     * 新增|编辑案例
     *
     * @param fieldCaseDTO
     * @param id
     * @param admin
     */
    public void save(FieldCaseDTO fieldCaseDTO, Integer id, Admin admin) {
        FieldCase fieldCase;
        Date now = new Date();
        FileVO oldCover = null;
        List<FileVO> oldFiles = null;
        String oldDetail = null;
        if (id == null) {
            fieldCase = FieldCase
                    .builder()
                    .createAdminId(admin.getId())
                    .createAdminName(admin.getNickName())
                    .createTime(now)
                    .build();
        } else {
            fieldCase = get(id);
            fieldCase.setUpdateAdminId(admin.getId());
            fieldCase.setUpdateAdminName(admin.getNickName());
            fieldCase.setUpdateTime(now);

            oldCover = fieldCase.getCover() == null ? null : JSON.parseObject(fieldCase.getCover(), FileVO.class);
            oldFiles = fieldCase.getFiles() == null ? null : JSON.parseArray(fieldCase.getFiles(), FileVO.class);
            oldDetail = fieldCase.getDetail();
        }

        fieldCaseMapstruct.copyFieldCase(fieldCase, fieldCaseDTO);

        if (id == null) {
            fieldCaseMapper.insert(fieldCase);

            //删除数据库临时文件
        } else {
            fieldCaseMapper.updateById(fieldCase);
        }

        //清理附件
        fileUploadService.deleteFileForUpdate(
                ArraysExtendUtil.mergerArraysList(Arrays.asList(fieldCaseDTO.getCover()), fieldCaseDTO.getFiles()),
                ArraysExtendUtil.mergerArraysList(Arrays.asList(oldCover), oldFiles)
        );

        //清理富文本图片
        List<String> oldImgUrl = ImageUtil.getImgTagUrl(oldDetail);
        List<String> newImgUrl = ImageUtil.getImgTagUrl(fieldCaseDTO.getDetail());
        fileUploadService.deleteFileForUpdateByURL(newImgUrl, oldImgUrl);
    }

    /**
     * 删除案例
     *
     * @param id
     */
    public void delete(Integer id) {
        FieldCase fieldCase = get(id);
        fieldCaseMapper.deleteById(id);
        doDeleteAfter(fieldCase);
    }

    /**
     * 删除案例之后的操作
     *
     * @param fieldCase
     */
    public void doDeleteAfter(FieldCase fieldCase) {
        //删除旧文件
        if (!StringUtils.isEmpty(fieldCase.getCover())) {
            fileUploadService.deleteFileByFileVO(Arrays.asList(JSON.parseObject(fieldCase.getCover(), FileVO.class)), true, true);
        }
        if (!StringUtils.isEmpty(fieldCase.getFiles())) {
            fileUploadService.deleteFileByFileVO(JSON.parseArray(fieldCase.getFiles(), FileVO.class), true, true);
        }

        //删除富文本图片
        List<String> imgUrls = ImageUtil.getImgTagUrl(fieldCase.getDetail());
        fileUploadService.deleteFileForUpdateByURL(imgUrls, null);
    }

    /**
     * 下载案例，仅仅用于统计次数
     *
     * @param id
     */
    public void download(Integer id) {
        fieldCaseMapper.addDownloadCnt(id, 1);
    }

    /**
     * 案例贡献人排名
     *
     * @param top
     * @return
     */
    public List<ContributorTopVO> contributorTop(Integer top) {
        return fieldCaseMapper.contributorTop(top);
    }
}
